﻿using System;
using System.Collections.Generic;
using System.Xml.Linq;
using unTroublemaker.Conditions;

namespace unTroublemaker.Parsing
{
    public class ServiceConditionParser : ISpecificationParser
    {
        public ISpecificationItem Parse(XElement element, ISpecificationParser genericParser)
        {
            var parseErrors = new List<string>();

            var running = (string) element.Attribute("running");
            var startupType = (string)element.Attribute("startup-type");

            var name = (string)element.Attribute("name");
            if(string.IsNullOrEmpty(name))
                parseErrors.Add("Attribute name needs to be specified");

            if (!string.IsNullOrEmpty(running))
            {
                bool expectedValue;
                if (bool.TryParse(running, out expectedValue))
                    return ServiceCondition.CheckRunning(name, expectedValue);

                parseErrors.Add("Failed to parse running value '" + running + "' to boolean.");
            }
            else if (!string.IsNullOrEmpty(startupType))
            {
                if(ServiceCondition.IsStartupType(startupType))
                    return ServiceCondition.CheckStartupType(name, startupType);
                
                parseErrors.Add("Invalid startup type " + startupType + ".");
            }


            parseErrors.Add("Either running or startup-type attribute needs to be specified");
            throw new Exception("Failed to parse check-service: " + string.Join("\r\n", parseErrors));
        }

        public string ElementName { get { return "check-service"; } }
    }
}
